from functools import wraps

from flask import Markup, flash, url_for, redirect, abort
from flask_login import current_user

# 权限验证装饰器
def confirm_required(func):
    """用户需要确认"""
    @wraps(func)
    def decorated_function(*args, **kwargs):
        if not current_user.confirmed:
            message = Markup(
                '请首先确认用户账号。'
                '邮件没有回复？'
                '<a class="alert-link" href="%s">重发确认邮件</a>' %
                url_for('auth.resend_confirm_email'))
            flash(message, 'warning')
            return redirect(url_for('home.index'))
        return func(*args, **kwargs)
    return decorated_function


def permission_required(permission_name):
    """访问需要权限"""
    # 参数：权限名称
    def decorator(func):
        @wraps(func)
        def decorated_function(*args, **kwargs):
            if not current_user.can(permission_name):       # 对当前用户调用can()方法验证
                abort(403)                                  # 没有权限返回403
            return func(*args, **kwargs)
        return decorated_function
    return decorator


def admin_required(func):
    """系统管理员权限验证"""
    return permission_required('ADMINISTER')(func)